<template>
  <div class="user-orders-container">
     <nav class="navbar">
      <button class="back-btn" @click="goBack">← 返回</button>
    </nav>
    <div class="orders-header">
      <h2>我的订单</h2>
      <a-input-search
        v-model:value="searchText"
        placeholder="搜索订单号或商品名称..."
        style="width: 300px"
        @search="handleSearch"
        enter-button
      />
    </div>
    
    <a-tabs v-model:activeKey="activeStatus" @change="handleTabChange">
      <a-tab-pane key="all" tab="全部订单" />
      <a-tab-pane key="0" tab="待支付" />
      <a-tab-pane key="1" tab="已支付" />
    </a-tabs>
    
    <a-spin :spinning="loading">
      <div class="orders-list">
        <!-- 显示筛选后的订单 -->
        <div v-for="order in filteredOrders" :key="order.order_id" class="order-card">
          <div class="order-header">
            <span class="order-no">订单号: {{ order.order_no }}</span>
            <span class="order-status" :class="getStatusClass(order.order_status)">
              {{ getStatusText(order.order_status) }}
            </span>
          </div>
          
          <div class="order-time">
            下单时间: {{ formatTime(order.create_time) }}
          </div>
          
          <div class="order-items">
            <div v-for="item in order.items" :key="item.detail_id" class="order-item">
              <img :src="item.product_info?.mainImage" class="item-image" />
              <div class="item-info">
                <div class="item-name">{{ item.product_info?.product_name }}</div>
                <div class="item-spec" v-if="item.product_info?.specification">
                  规格: {{ item.product_info.specification }}
                </div>
                <div class="item-desc" v-if="item.product_info?.description">
                  {{ item.product_info.description }}
                </div>
                <div class="item-price">¥{{ item.product_price }} x {{ item.quantity }}</div>
              </div>
              <a-button 
                type="link" 
                @click="viewProductDetail(item.product_id)"
                class="view-product-btn"
              >
                查看商品
              </a-button>
            </div>
          </div>
          
          <div class="order-footer">
            <div class="order-total">
              实付金额: <span class="total-price">¥{{ order.pay_amount }}</span>
            </div>
            
            <!-- 倒计时显示 - 仅对未支付订单 -->
            <div v-if="order.order_status === 0" class="countdown-container">
              <span class="countdown-label">订单将在</span>
              <span class="countdown-time" :class="{ 'countdown-warning': order.remainingTime < 3600 }">
                {{ formatCountdown(order.remainingTime) }}
              </span>
              <span class="countdown-label">后自动取消</span>
            </div>
            
            <div class="order-actions">
              <a-button v-if="order.order_status === 0" type="primary" @click="handlePay(order)">
                立即支付
              </a-button>
              <a-button @click="viewOrderDetail(order.order_no)">
                订单详情
              </a-button>
              <a-button v-if="order.order_status === 0" @click="cancelOrder(order)">
                取消订单
              </a-button>
               <a-button v-if="order.order_status === 1" @click="refundOrder(order)">
                极速退款
              </a-button>
            </div>
          </div>
        </div>
        
        <a-empty v-if="filteredOrders.length === 0" :description="emptyDescription" />
      </div>
      
      <div class="pagination">
        <a-pagination
          v-model:current="currentPage"
          v-model:pageSize="pageSize"
          :total="total"
          show-less-items
          @change="fetchOrders"
        />
      </div>
    </a-spin>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { 
  getOrdersByUserId, 
  updateOrder,
  deleteByOrderNo
} from '@/api/mall/bizOrderController'
import { getByOrderNo } from '@/api/mall/bizOrderDetailController'
import { useAuthStore } from '@/stores/authStore'
import { getProductById } from '@/api/mall/bizProductController'
import { createOrder1 } from '@/api/mall/alipayController'
  
import { applyRefund} from '@/api/cart/bizRefundRequestController'
const router = useRouter()
const authStore = useAuthStore()

// 订单数据
const orders = ref<OrderWithDetails[]>([])
const loading = ref(false)
const searchText = ref('')
const activeStatus = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const countdownInterval = ref<number | null>(null)

interface OrderWithDetails {
  order_id: number
  order_no: string
  order_status: number
  create_time: string
  pay_amount: number
  items: OrderItemDetail[]
  remainingTime: number
  isExpired: boolean
  create_timestamp: number // 添加时间戳用于排序
}

interface OrderItemDetail {
  detail_id: number
  product_id: number
  quantity: number
  product_price: number
  product_info: ProductInfo | null
}

interface ProductInfo {
  productId: number;
  sellerUserId: number;
  productName: string;
  description?: string;
  categoryId?: number;
  price: number;
  stock: number;
  sale?: number;
  status: 0 | 1;
  mainImage: string;
  detailImage?: string;
}

// 计算空状态描述
const emptyDescription = computed(() => {
  if (searchText.value) {
    return `没有找到包含"${searchText.value}"的订单`
  }
  switch (activeStatus.value) {
    case '0': return '暂无待支付订单'
    case '1': return '暂无已支付订单'
    default: return '暂无订单'
  }
})

// 排序函数：未支付订单优先，按时间倒序
const sortOrders = (orders: OrderWithDetails[]) => {
  return orders.sort((a, b) => {
    // 首先按状态排序：未支付(0) > 已支付(1)
    if (a.order_status !== b.order_status) {
      return a.order_status - b.order_status
    }
    // 相同状态下按时间倒序（最新的在前）
    return b.create_timestamp - a.create_timestamp
  })
}

// 筛选和搜索订单
const filteredOrders = computed(() => {
  let filtered = orders.value
  
  // 按状态筛选
  if (activeStatus.value !== 'all') {
    const status = parseInt(activeStatus.value)
    filtered = filtered.filter(order => order.order_status === status)
  }
  
  // 搜索功能
  if (searchText.value.trim()) {
    const searchTerm = searchText.value.toLowerCase().trim()
    filtered = filtered.filter(order => {
      // 搜索订单号
      if (order.order_no.toLowerCase().includes(searchTerm)) {
        return true
      }
      
      // 搜索商品名称
      return order.items.some(item => 
        item.product_info?.product_name?.toLowerCase().includes(searchTerm)
      )
    })
  }
  
  return sortOrders(filtered)
})

// 格式化倒计时显示
const formatCountdown = (seconds: number) => {
  if (seconds <= 0) return '00:00:00'
  
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 计算订单剩余时间
const calculateRemainingTime = (createTime: string): number => {
  const createDate = new Date(createTime).getTime()
  const now = Date.now()
  const elapsedTime = Math.floor((now - createDate) / 1000)
  const totalValidTime = 24 * 60 * 60
  return Math.max(0, totalValidTime - elapsedTime)
}

// 检查订单是否过期
const checkOrderExpired = (createTime: string): boolean => {
  const createDate = new Date(createTime).getTime()
  const now = Date.now()
  const elapsedHours = (now - createDate) / (1000 * 60 * 60)
  return elapsedHours >= 24
}

// 更新倒计时
const updateAllCountdowns = () => {
  orders.value.forEach(order => {
    if (order.order_status === 0) {
      order.remainingTime = calculateRemainingTime(order.create_time)
      order.isExpired = order.remainingTime <= 0
    }
  })
}

// 启动倒计时定时器
const startCountdownTimer = () => {
  if (countdownInterval.value) {
    clearInterval(countdownInterval.value)
  }
  countdownInterval.value = setInterval(updateAllCountdowns, 1000)
}

// 标签切换处理
const handleTabChange = () => {
  currentPage.value = 1
  searchText.value = '' // 切换标签时清空搜索
  fetchOrders()
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  // 不需要重新获取数据，使用computed过滤即可
}

const viewProductDetail = (productId: number) => {
  router.push({
    name: 'detailShop',
    params: { goodsId: productId }
  })
}

// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true
    orders.value = []
    
    const ordersRes = await getOrdersByUserId({ userId: authStore.userInfo.id })
    console.log('订单响应:', ordersRes)
    
    if (!ordersRes || !ordersRes.length) {
      return
    }
    
    for (const order of ordersRes) {
      try {
        // 跳过已过期的未支付订单
        if (order.orderStatus === 0) {
          const isExpired = checkOrderExpired(order.createTime)
          if (isExpired) {
            console.log(`未支付订单 ${order.orderNo} 已过期，跳过`)
            continue
          }
        }
        
        // 跳过已完成订单（status=2）
        if (order.orderStatus === 2) {
          continue
        }
        
        const detailsRes = await getByOrderNo({ orderNo: order.orderNo })
        const details = Array.isArray(detailsRes?.data) ? detailsRes.data : []
        
        const items: OrderItemDetail[] = []
        for (const item of details) {
          try {
            const productRes = await getProductById({ productId: item.productId })
            const product = productRes?.data?.[0] || null
            
            items.push({
              detail_id: item.detailId,
              product_id: item.productId,
              quantity: item.quantity,
              product_price: item.productPrice,
              product_info: product ? {
                product_id: product.productId,
                seller_user_id: product.sellerUserId,
                product_name: product.productName,
                description: product.description,
                category_id: product.categoryId,
                price: product.price,
                stock: product.stock,
                sale: product.sale,
                status: product.status,
                main_image: product.mainImage,
                detail_image: product.detailImage
              } : null
            })
          } catch (productError) {
            console.error(`获取商品 ${item.productId} 失败:`, productError)
            items.push({ ...item, product_info: null })
          }
        }
        
        const remainingTime = order.orderStatus === 0 ? calculateRemainingTime(order.createTime) : 0
        const isExpired = order.orderStatus === 0 ? remainingTime <= 0 : false
        
        orders.value.push({
          order_id: order.orderId,
          order_no: order.orderNo,
          order_status: order.orderStatus,
          create_time: order.createTime,
          pay_amount: order.payAmount,
          items,
          remainingTime,
          isExpired,
          create_timestamp: new Date(order.createTime).getTime() // 添加时间戳
        })
      } catch (orderError) {
        console.error(`获取订单 ${order.orderNo} 详情失败:`, orderError)
      }
    }
    
    // 初始排序
    orders.value = sortOrders(orders.value)
    startCountdownTimer()
    
  } catch (error) {
    message.error('获取订单列表失败')
    console.error('订单列表加载错误:', error)
  } finally {
    loading.value = false
  }
}

// 订单状态文本和样式
const getStatusText = (status: number) => {
  const statusMap = ['待支付', '已支付', '已完成']
  return statusMap[status] || '未知状态'
}

const getStatusClass = (status: number) => {
  const classMap = ['status-waiting', 'status-paid', 'status-completed']
  return classMap[status] || ''
}

// 格式化时间
const formatTime = (time: string) => {
  return new Date(time).toLocaleString()
}

const viewOrderDetail = (orderNo: string) => {
  router.push({
    name: 'orderDetail',
    params: { orderNo }
  })
}


const refundOrder = (order: OrderWithDetails) => {
  router.push({
    name: 'Refund',
    query: {
      orderNo: order.order_no,
      payAmount: order.pay_amount.toString()
    }
  })
}



const cancelOrder = async (order) => {
  try {
    await deleteByOrderNo({ orderNo: order.order_no })
    message.success('订单已取消')
    // await applyRefund({ orderNo: order.order_no })
    fetchOrders()
  } catch (error) {
    message.error('取消订单失败')
    console.error(error)
  }
}

const handlePay = async (order) => {
  try {
    const productNames = order.items.map(item => {
      return item.product_info?.product_name || '未知商品';
    });
    
    const subject = productNames.join(', ');
    
    const params = {
      orderNo: order.order_no,
      amount: order.pay_amount,
      subject: subject
    }
    
    const res = await createOrder1(params)
    
    const payWindow = window.open('', '_blank')
    if (payWindow) {
      payWindow.document.write(res)
      payWindow.document.close()
    }
    
  } catch (error) {
    console.error('支付失败:', error)
    message.error(`支付失败: ${error instanceof Error ? error.message : '未知错误'}`)
  }
}
// 返回上一页
const goBack = () => {
  router.back()
}
// 组件卸载时清除定时器
onUnmounted(() => {
  if (countdownInterval.value) {
    clearInterval(countdownInterval.value)
    countdownInterval.value = null
  }
})

// 监听搜索词变化，实时过滤
watch(searchText, (newValue) => {
  if (!newValue.trim()) {
    // 清空搜索时，重新显示所有订单
    currentPage.value = 1
  }
})

// 初始化加载
onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
/* 样式保持不变，与之前相同 */
.user-orders-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.orders-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.orders-list {
  margin-top: 20px;
}

.order-card {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  background: #fff;
}

.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.order-no {
  font-weight: 500;
}

.order-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 14px;
}

.status-waiting {
  background: #fff7e6;
  color: #fa8c16;
}

.status-paid {
  background: #e6f7ff;
  color: #1890ff;
}

.status-completed {
  background: #f6ffed;
  color: #52c41a;
}

.order-time {
  color: #999;
  margin-bottom: 16px;
  font-size: 14px;
}

.order-items {
  margin-bottom: 16px;
}

.order-item {
  display: flex;
  margin-bottom: 12px;
}

.item-image {
  width: 80px;
  height: 60px;
  object-fit: cover;
  margin-right: 12px;
  border-radius: 4px;
}

.item-info {
  flex: 1;
}

.item-name {
  margin-bottom: 4px;
}

.item-price {
  color: #666;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.order-total {
  font-size: 16px;
}

.total-price {
  font-weight: 600;
  color: #f5222d;
  font-size: 18px;
}

.order-actions {
  display: flex;
  gap: 8px;
}

.pagination {
  margin-top: 24px;
  text-align: center;
}

.item-spec {
  color: #666;
  font-size: 14px;
  margin: 4px 0;
}

.item-desc {
  color: #999;
  font-size: 13px;
  margin: 4px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.view-product-btn {
  padding: 0;
  height: auto;
}

.countdown-container {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 8px 0;
}

.countdown-label {
  color: #666;
  font-size: 14px;
}

.countdown-time {
  font-family: 'Courier New', monospace;
  font-size: 16px;
  font-weight: 600;
  color: #1890ff;
  padding: 4px 8px;
  background: #e6f7ff;
  border-radius: 4px;
  min-width: 85px;
  text-align: center;
}

.countdown-warning {
  color: #ff4d4f;
  background: #fff2f0;
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.7; }
  100% { opacity: 1; }
}
.back-btn {
  color: #333;
  background: transparent;
  border: none;
  cursor: pointer;
  font-size: 16px;
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 12px;
  border-radius: 4px;
}
</style>